import Vue from "vue";

// 获取商品分类列表
async function getCateList() {
  const formData = new FormData();
  formData.append("page", 1);
  formData.append("rows", 30);
  const { data: res } = await Vue.prototype.$http.post("categoryList", formData);
  // console.log(res, "分类");
  if (res.code != 0) return Vue.prototype.$message("获取商品分类失败！");

  const parentList = [];
  const childrenList = [];
  res.data.forEach((item) => {
    const obj = {};
    obj.sort = item.sort;
    obj.id = obj.value = item.id;
    obj.label = item.info_name;
    if (!item.parent_id || item.parent_id == "undefined") {
      // 此时为父级
      obj.children = [];
      parentList.unshift(obj);
    } else {
      // 此时为子级
      obj.parent_id = item.parent_id;
      childrenList.push(obj);
    }
  });
  parentList.forEach((item) => {
    childrenList.forEach((item2) => {
      if (item.id == item2.parent_id) {
        item2.parent_value = item.label;
        item.children.push(item2);
      }
    });
  });
  parentList.forEach((item) => {
    item.children && item.children.length != 0 && item.children.sort((a, b) => a.sort - b.sort);
  });
  parentList.sort((a, b) => a.sort - b.sort);
  // console.log(parentList);
  return parentList;
}
export default getCateList;
